<?php

/**
 * 微信配置
 */

namespace app\admin\controller;

use think\facade\View;
use app\api\controller\WechatApi;
use think\facade\Db;
use think\facade\Lang;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Wechat extends AdminControl {

    public function initialize() {
        parent::initialize(); // TODO: Change the autogenerated stub
        Lang::load(base_path() . 'admin/lang/' . config('lang.default_lang') . '/wechat.lang.php');
    }

    //公众号配置
    public function setting() {
        $wechat_model = model('wechat');
        if (!request()->isPost()) {
            //获取公众号配置信息
            $wx_config = $wechat_model->getOneWxconfig();
            View::assign('wx_config', $wx_config);
            //接口地址
            $wx_apiurl = HTTP_TYPE . $_SERVER['HTTP_HOST'] . substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'], 'index.php')) . 'api/Wechat/index';
            View::assign('wx_apiurl', $wx_apiurl);
            return View::fetch();
        } else {
            $data = [
                'token' => input('post.wx_token'),
                'appid' => input('post.wx_appid'),
                'appsecret' => input('post.wx_AppSecret'),
                'wxname' => input('post.wx_name'),
                'xcx_appid' => input('post.xcx_appid'),
                'xcx_appsecret' => input('post.xcx_AppSecret'),
            ];
            //公众号二维码图片待处理
            $id = input('param.wx_id');
            if (empty($id)) {
                $res = $wechat_model->addWxconfig($data);
            } else {
                $res = $wechat_model->editWxconfig(array('id' => $id), $data);
            }
            if ($res) {
                $this->success(lang('ds_common_op_succ'));
            } else {
                $this->error(lang('ds_common_op_fail'));
            }
        }
    }

    //公众号菜单
    public function menu() {
        $wechat_model = model('wechat');
        $menu_list = $wechat_model->getWxmenuList(array(array('pid','=',0)));
        $menu_json=array();
        foreach($menu_list as $key => $val){
            $menu_json[$key]=array();
            $menu_json[$key][]=array('name'=>'name','value'=>$val['name']);
            if($val['type']){
                $menu_json[$key][]=array('name'=>'type','value'=>$val['type']);
            }
            if($val['value']){
                $val['value']= json_decode($val['value'], true);
                foreach($val['value'] as $k => $v){
                    if($k=='url'){
                        if($val['type']=='view'){
                            $menu_json[$key][]=array('name'=>'url1','value'=>$v);
                        }else if($val['type']=='miniprogram'){
                            $menu_json[$key][]=array('name'=>'url2','value'=>$v);
                        }
                    }else{
                        $menu_json[$key][]=array('name'=>$k,'value'=>$v);
                    }
                }
            }
            $menu_json[$key][]=array('child'=>[]);
            $menu_sub_list=$wechat_model->getWxmenuList(array(array('pid','=',$val['id'])));
            $menu_list[$key]['child']=$menu_sub_list;
            if(!empty($menu_sub_list)){
                foreach($menu_sub_list as $key1 => $val1){
                    $temp=array();
                    $temp[]=array('name'=>'name','value'=>$val1['name']);
                    if($val1['type']){
                        $temp[]=array('name'=>'type','value'=>$val1['type']);
                    }
                    if($val1['value']){
                        $val1['value']= json_decode($val1['value'], true);
                        foreach($val1['value'] as $k => $v){
                            if($k=='url'){
                                if($val1['type']=='view'){
                                    $temp[]=array('name'=>'url1','value'=>$v);
                                }else if($val1['type']=='miniprogram'){
                                    $temp[]=array('name'=>'url2','value'=>$v);
                                }
                            }else{
                                $temp[]=array('name'=>$k,'value'=>$v);
                            }
                        }
                    }
                    $menu_json[$key][count($menu_json[$key])-1]['child'][]=$temp;
                }
            }
        }
        View::assign('menu_list', $menu_list);
        View::assign('menu_json', $menu_json);
        $this->setAdminCurItem('menu');
        return View::fetch();
    }
    
    public function add_menu(){
        $menus=input('param.menus/a');
        $result='';
        $menu_list=array();
        Db::startTrans();
        try {
            $wechat_model = model('wechat');
            $condition=array(array('id','>',0));
            $wechat_model->delWxmenu($condition);
            foreach($menus as $key => $val){

                    $temp=array();
                    foreach($val as $k => $v){
                        if($k!=(count($val)-1)){
                            $temp[$v['name']]=$v['value'];
                        }
                    }
                    $id=count($menu_list)+1;
                    $menu_list[]=array('id'=>$id,'pid'=>0,'child_count'=>isset($val[count($val)-1]['child'])?count($val[count($val)-1]['child']):0,'value'=>$temp,'index1'=>$key,'index2'=>-1);
                    if(isset($val[count($val)-1]['child'])){
                        foreach($val[count($val)-1]['child'] as $k1 => $v1){
                        $temp=array();
                        foreach($v1 as $k => $v){
                            $temp[$v['name']]=$v['value'];
                        }
                        $menu_list[]=array('id'=>count($menu_list)+1,'pid'=>$id,'value'=>$temp,'index1'=>$key,'index2'=>$k1);
                    }
                    }
            }
            $menu_array=array();
            foreach($menu_list as $val){
                if(trim($val['value']['name'])==''){
                    $result=array('index1'=>$val['index1'],'index2'=>$val['index2'],'name'=>'name');
                    throw new \think\Exception('', 10006);
                }
                if(isset($val['child_count']) && $val['child_count']>0){
                    $menu_array[]=array(
                        'id'=>$val['id'],
                        'pid'=>$val['pid'],
                        'name'=>$val['value']['name'],
                        'type'=>'',
                        'value'=>''
                    );
                }else{
                    $temp=array(
                        'id'=>$val['id'],
                        'pid'=>$val['pid'],
                        'name'=>$val['value']['name'],
                        'type'=>$val['value']['type'],
                    );
                    switch($val['value']['type']){
                        case 'media_id':
                            if(trim($val['value']['media_id'])==''){
                                $result=array('index1'=>$val['index1'],'index2'=>$val['index2'],'name'=>'media_id');
                                throw new \think\Exception('', 10006);
                            }
                            $temp['value']=json_encode(array('media_id'=>$val['value']['media_id']));
                            break;
                        case 'click':
                            if(trim($val['value']['key'])==''){
                                $result=array('index1'=>$val['index1'],'index2'=>$val['index2'],'name'=>'key');
                                throw new \think\Exception('', 10006);
                            }
                            $temp['value']=json_encode(array('key'=>$val['value']['key']));
                            break;
                        case 'view':
                            if(trim($val['value']['url1'])==''){
                                $result=array('index1'=>$val['index1'],'index2'=>$val['index2'],'name'=>'url1');
                                throw new \think\Exception('', 10006);
                            }
                            $temp['value']=json_encode(array('url'=>$val['value']['url1']));
                            break;
                        case 'miniprogram':
                            if(trim($val['value']['url2'])=='' || trim($val['value']['appid'])=='' || trim($val['value']['pagepath'])==''){
                                $result=array('index1'=>$val['index1'],'index2'=>$val['index2'],'name'=>((trim($val['value']['url2'])=='')?'url2':((trim($val['value']['appid'])=='')?'appid':'pagepath')));
                                throw new \think\Exception('', 10006);
                            }
                            $temp['value']=json_encode(array('url'=>$val['value']['url2'],'appid'=>$val['value']['appid'],'pagepath'=>$val['value']['pagepath']));
                            break;
                        default:
                            $result=array('index1'=>$val['index1'],'index2'=>$val['index2'],'name'=>'type');
                            throw new \think\Exception('', 10006);
                    }
                    $menu_array[]=$temp;
                }
            }
            if(!empty($menu_array)){
                Db::name('wxmenu')->insertAll($menu_array);
            }
        } catch (\Exception $e) {
            Db::rollback();
            ds_json_encode(10001, $e->getMessage(),$result);
        }
        Db::commit();
        ds_json_encode(10000, lang('ds_common_op_succ'));
    }


    //更新公众号菜单
    public function pub_menu() {

        //获取父级菜单
        $wechat_model = model('wechat');
        //获取菜单
        $config = $wechat_model->getOneWxconfig();

        $p_menus = $wechat_model->getWxmenuList(array('pid' => 0), 'id ASC');
        $p_menus = ds_change_arraykey($p_menus, 'id');

        $post_str = $this->convert_menu($p_menus);

        // http post请求
        if (!count($p_menus) > 0) {
            $this->error(lang('no_menu'), 'Wechat/menu');
            exit;
        }
        //查看access_token是否过期
        $wechat = new WechatApi($config);
        $expire_time = $config['expires_in'];
        if ($expire_time > TIMESTAMP) {
            //有效期内
            $wechat->access_token_ = $config['access_token'];
        } else {
            $access_token = $wechat->checkAuth();
            if ($access_token == FALSE) {
                $this->error(lang('ds_common_op_fail') . $wechat->errCode . $wechat->errMsg, 'Wechat/menu');
            }
            $web_expires = TIMESTAMP + 7000; // 提前200秒过期
            $condition = array();
            $condition[] = array('id', '=', $config['id']);
            $data = array('access_token' => $access_token, 'expires_in' => $web_expires);
            $wechat_model->editWxconfig($condition, $data);
        }
        $return = $wechat->createMenu($post_str);
        if ($return) {
            $this->success(lang('ds_common_op_succ'), 'Wechat/menu');
        } else {
            $this->error(lang('ds_common_op_fail') . $wechat->errCode . $wechat->errMsg);
        }
    }

    //菜单转换
    private function convert_menu($p_menus) {
        $wechat_model = model('wechat');
        $new_arr = array();
        $count = 0;
        foreach ($p_menus as $k => $v) {
            $new_arr[$count]['name'] = $v['name'];

            //获取子菜单
            $c_menus = $wechat_model->getMenulist(array('pid' => $k));
            if ($c_menus) {
                foreach ($c_menus as $kk => $vv) {
                    $add = array();
                    $add['name'] = $vv['name'];
                    $add['type'] = $vv['type'];
                    $add=array_merge($add, json_decode($vv['value'],true));
                    $new_arr[$count]['sub_button'][] = $add;
                }
            } else {
                $new_arr[$count]['type'] = $v['type'];
                $new_arr[$count]=array_merge($new_arr[$count], json_decode($v['value'],true));
            }
            $count++;
        }

        return array('button' => $new_arr);
    }

    /**
     * 关键字文本回复
     */
    public function k_text() {
        $wechat_model = model('wechat');
        $wechat = $wechat_model->getOneWxconfig();
        if (empty($wechat)) {
            $this->error(lang('please_set_wechat_config'), 'Wechat/setting');
        }
        $lists = $wechat_model->getWxkeywordList(array('type' => 'TEXT'), 'k.id,k.keyword,t.text', 10, 't.createtime DESC');
        View::assign('lists', $lists);
        View::assign('show_page', $wechat_model->page_info->render());
        return View::fetch();
    }

    /*
     * 添加文本回复
     */

    public function text_form() {
        $wechat_model = model('wechat');
        $wechat = $wechat_model->getOneWxconfig();
        if (empty($wechat)) {
            $this->error(lang('please_set_wechat_config'), 'Wechat/setting');
        }
        if (request()->isPost()) {
            $kid = input('param.id');
            $add['keyword'] = input('param.keyword');
            $add['text'] = input('param.text');
            if (empty($kid)) {
                //添加模式
                $add['createtime'] = TIMESTAMP;
                $add['pid'] = $wechat_model->addWxtext($add);
                unset($add['text']);
                unset($add['createtime']);
                $add['type'] = 'TEXT';
                $row = $wechat_model->addWxkeyword($add);
            } else {
                //编辑模式
                $data = $wechat_model->getOneWxkeyword(array('id' => $kid));
                if ($data) {
                    $update['keyword'] = $add['keyword'];
                    $wechat_model->editWxkeyword(array('id' => $kid), $update);
                    $row = $wechat_model->editWxtext(array('id' => $data['pid']), $add);
                }
            }
            $row >= 0 ? dsLayerOpenSuccess(lang('ds_common_op_succ')) : $this->error(lang('ds_common_op_fail'), 'Wechat/k_text');
            exit;
        } else {
            //编辑状态
            $id = intval(input('param.id'));
            $key = array();
            if ($id) {
                $where = "k.id={$id} AND k.type='TEXT'";
                $res = Db::name('wxkeyword')->alias('k')->join('wxtext t', 't.id=k.id', 'LEFT')->where($where)->field('k.id,k.keyword,t.text')->find();
                View::assign('key', $res);
            }
            return View::fetch();
        }
    }

    /*
     * 删除文本回复
     */

    public function del_text() {
        $wechat_model = model('wechat');
        $id = input('param.id');
        $row = $wechat_model->getOneWxkeyword(array('id' => $id));
        if ($row) {
            $wechat_model->delWxkeyword(array('id' => $id));
            $wechat_model->delWxtext(array('id' => $row['pid']));
            ds_json_encode(10000, lang('ds_common_del_succ'));
        } else {
            ds_json_encode(10001, lang('ds_common_del_fail'));
        }
    }

    /**
     * 删除消息推送
     */
    public function del_wxmsg() {
        $wechat_model = model('wechat');
        $id = input('param.id');
        $id_array = ds_delete_param($id);
        if ($id_array === FALSE) {
            ds_json_encode(10001, lang('param_error'));
        }
        $condition = array(array('id', 'in', $id_array));
        $result = $wechat_model->delWxmsg($condition);
        if ($result) {
            ds_json_encode(10000, lang('ds_common_del_succ'));
        } else {
            ds_json_encode(10001, lang('ds_common_del_fail'));
        }
    }

    /*     * 微信注册会员列表 */

    public function member() {
        $wechat_model = model('wechat');
        $wxmember_list = $wechat_model->getWxmemberList();
        foreach($wxmember_list as $key => $val){
          @$wxmember_list[$key]['member_wxinfo']=unserialize($val['member_wxinfo']);
        }
        View::assign('show_page', $wechat_model->page_info->render());
        View::assign('wxmember_list', $wxmember_list);
        return View::fetch('member');
    }

    /*     * 消息推送 */

    public function msend() {
        $touser = input('param.openid');
        $id = input('param.member_id');
        if (request()->isPost()) {
            $wechat_model = model('wechat');
            $config = $wechat_model->getOneWxconfig();
            $wechat = new WechatApi($config);
            $type = input('param.type');
            if ($type == 'text') {
                //发送文本消息
                $content = input('param.text');
                $send = array(
                    'touser' => $touser, 'msgtype' => 'text', 'text' => array('content' => $content)
                );
            } else {
                //发送图文消息
                $title = input('param.title');
                $description = input('param.description');
                $url = input('param.url');
                $picUrl = '';
                if (!empty($_FILES['s_pic']['name'])) {
                    $prefix = $id;
                    $file_name = $prefix . '_' . date('YmdHis') . rand(10000, 99999) . '.png';
                    $res = ds_upload_pic(DIR_ADMIN . DIRECTORY_SEPARATOR . 'wechat', 's_pic', $file_name);
                    if ($res['code']) {
                        $file_name = $res['data']['file_name'];
                    } else {
                        $this->error($res['msg']);
                    }

                    $picUrl = ds_get_pic( DIR_ADMIN . DIRECTORY_SEPARATOR . 'wechat' , $file_name);
                }
                $content = array(
                    array(
                        'title' => $title, 'description' => $description, 'url' => $url, 'picurl' => $picUrl
                    )
                );
                $send = array(
                    'touser' => $touser, 'msgtype' => 'news', 'news' => array('articles' => $content)
                );
            }

            $SendInfo = serialize($send);
            $data['member_id'] = $id;
            $data['content'] = $SendInfo;
            $data['createtime'] = TIMESTAMP;
            $ret = $wechat->sendCustomMessage($send);
            if ($ret) {
                //添加至推送列表
                $data['issend'] = '1';
                $wechat_model->addWxmsg($data);
                dsLayerOpenSuccess(lang('ds_common_op_succ'));
            } else {
                $data['issend'] = '0';
                $wechat_model->addWxmsg($data);
                $this->error(lang('ds_common_op_fail') . $wechat->errCode . $wechat->errMsg);
            }
        } else {
            return View::fetch();
        }
    }

    /*     * 消息推送列表 */

    public function SendList() {
        $wechat_model = model('wechat');
        $list = $wechat_model->getWxmsgList();
        foreach ($list as $key => $val) {
            $info = unserialize($val['content']);
            $type = $info['msgtype'];
            $list[$key]['type'] = $type == 'text' ? lang('message_type_text') : lang('message_type_news');
            if ($type == 'text') {
                $list[$key]['content'] = $info['text']['content'];
            } else {
                $content = $info['news']['articles']['0'];
                $content = json_encode($content);
                $list[$key]['content'] = "<a href='javascript:void(0);' class='news' content=''>查看图文消息</a>";
                /* View::assign('title',$content['title']);
                  View::assign('description',$content['description']);
                  View::assign('url',$content['url']);
                  echo View::fetch('news'); */
            }
        }
        View::assign('show_page', $wechat_model->page_info->render());
        View::assign('lists', $list);
        return View::fetch('list');
    }

    /*     * 消息群发 */

    public function Sendgroup() {
        if (request()->isPost()) {
            $m_info = model('wechat')->getWxmemberList();
            $openid = '';
            foreach ($m_info as $k => $val) {
                $openid .= $val['member_wxopenid'] . ',';
            }
            $openid = explode(',', $openid);
            $content = input('param.text');
            $send = array(
                'touser' => $openid,
                'msgtype' => 'text',
                'text' => array('content' => $content)
            );
            $config = model('wechat')->getOneWxconfig();
            $wechat = new WechatApi($config);
            $res = $wechat->massSend($send);
            if ($res) {
                dsLayerOpenSuccess(lang('ds_common_op_succ'));
            } else {
                $this->error(lang('ds_common_op_fail') . $wechat->errCode . $wechat->errMsg);
            }
        } else {
            return View::fetch('sendgroup');
        }
    }
    
    public function material(){
        $wechat_model = model('wechat');
        $wechat = $wechat_model->getOneWxconfig();
        if (empty($wechat)) {
            $this->error(lang('please_set_wechat_config'), 'Wechat/setting');
        }
        $template=array(
            'type'=>'news',
            'offset'=>(input('param.page',1)-1)*10,
            'count'=>10,
        );
        $res=$wechat_model->getMaterialList($template);
        if(!$res['code']){
            $this->error($res['msg']);
        }
        $paginate = Db::name('wxconfig')->paginate(10,$res['data']['total_count'],['query' => request()->param()]);
        View::assign('show_page', $paginate->render());
        View::assign('list', $res['data']['item']);
        $this->setAdminCurItem('material');
        return View::fetch();
    }
    
    public function material_select(){
        $wechat_model = model('wechat');
        $wechat = $wechat_model->getOneWxconfig();
        if (empty($wechat)) {
            $this->error(lang('please_set_wechat_config'), 'Wechat/setting');
        }
        $template=array(
            'type'=>'news',
            'offset'=>(input('param.page',1)-1)*10,
            'count'=>10,
        );
        $res=$wechat_model->getMaterialList($template);
        if(!$res['code']){
            $this->error($res['msg']);
        }
        $paginate = Db::name('wxconfig')->paginate(10,$res['data']['total_count'],['query' => request()->param()]);
        View::assign('show_page', $paginate->render());
        View::assign('list', $res['data']['item']);
        return View::fetch();
    }
    
    public function material_add(){
        if (request()->isPost()) {
            $wechat_model = model('wechat');
            $wechat = $wechat_model->getOneWxconfig();
            $temp=input('param.articles/a');
            $articles=array();
            foreach($temp as $key => $val){
                $a=array();
                foreach($val as $v){
                    if(in_array($v['name'],['thumb_media_id','title','author','content','content_source_url','need_open_comment','only_fans_can_comment'])){
                        if(in_array($v['name'],['thumb_media_id','title','content','content_source_url']) && $v['value']==''){
                            ds_json_encode(10001, '', array('index'=>$key,'name'=>$v['name']));
                        }
                        $a[$v['name']]=$v['value'];
                    }
                }
                $articles[]=$a;
            }
            $template=array(
                'articles'=>$articles
            );
            $res=$wechat_model->addMaterial($template);
            if(!$res['code']){
                ds_json_encode(10001, $res['msg']);
            }
            ds_json_encode(10000, lang('ds_common_op_succ'));
        }else{
            $this->setAdminCurItem('material_add');
            return View::fetch('material_form');
        }
    }
    
    public function material_edit(){
        $wechat_model = model('wechat');
        $wechat = $wechat_model->getOneWxconfig();
        $media_id=input('param.media_id');
        $res=$wechat_model->getMaterialInfo($media_id);
        if (request()->isPost()) {
            if(!$res['code']){
                ds_json_encode(10001, $res['msg']);
            }
            $material_info=$res['data']['news_item'];
            $temp=input('param.articles/a');
            $index=0;
            foreach($temp as $key => $val){
                $a=array();
                foreach($val as $v){
                    if(in_array($v['name'],['thumb_media_id','title','author','content','content_source_url','need_open_comment','only_fans_can_comment'])){
                        if(in_array($v['name'],['thumb_media_id','title','content','content_source_url']) && $v['value']==''){
                            ds_json_encode(10001, '', array('index'=>$key,'name'=>$v['name']));
                        }
                        $a[$v['name']]=$v['value'];
                    }
                }
                if(!isset($material_info[$index])){
                    ds_json_encode(10001, '图文消息（'.$index.'）不存在');
                }
                ksort($a);
                ksort($material_info[$index]);
                if(json_encode($a)!=json_encode($material_info[$index])){
                    $template=array(
                        'media_id'=>$media_id,
                        'index'=>$index,
                        'articles'=>$a
                    );
                    $res=$wechat_model->editMaterial($template);
                    if(!$res['code']){
                        ds_json_encode(10001, $res['msg']);
                    }
                }
                $index++;
            }
            ds_json_encode(10000, lang('ds_common_op_succ'));
        }else{
            if(!$res['code']){
                $this->error($res['msg']);
            }
            foreach($res['data']['news_item'] as $key => $val){
                $res['data']['news_item'][$key]['content']=str_replace('data-src','src',$val['content']);
            }
            View::assign('material_info', $res['data']['news_item']);
            $this->setAdminCurItem('material_edit');
            return View::fetch('material_form');
        }
    }
    
    public function material_del(){
        $wechat_model = model('wechat');
        $wechat = $wechat_model->getOneWxconfig();
        $res=$wechat_model->delMaterial(input('param.media_id'));
        if(!$res['code']){
            ds_json_encode(10001, $res['msg']);
        }
        ds_json_encode(10000, lang('ds_common_op_succ'));
    }
    
    public function get_material_image(){
        $wechat_model = model('wechat');
        $wechat = $wechat_model->getOneWxconfig();
        return $wechat_model->getMaterialInfo(input('param.media_id'),input('param.if_not_image')?false:true);
    }
    
    public function upload_material_image(){
        $type= intval(input('param.type'));
        $wechat_model = model('wechat');
        $wechat = $wechat_model->getOneWxconfig();
        $res=$wechat_model->uploadMaterialImage($_FILES['file'],$type);
        if(!$res['code']){
            ds_json_encode(10001, $res['msg']);
        }
        ds_json_encode(10000, '',$res['data']);
    }

    protected function getAdminItemList() {
        if(strpos(request()->action(),'material')!==false){
            $menu_array = array(
                array(
                    'name' => 'material',
                    'text' => lang('ds_list'),
                    'url' => (string) url('Wechat/material')
                ),
            );
            if(request()->action()=='material_edit'){
                $menu_array[]=array(
                    'name' => 'material_edit',
                    'text' => lang('ds_edit'),
                    'url' => 'javascript:void(0)'
                );
            }else{
                $menu_array[]=array(
                    'name' => 'material_add',
                    'text' => lang('ds_new'),
                    'url' => (string) url('Wechat/material_add')
                );
            }
        }else{
            $menu_array = array(
                array(
                    'name' => 'menu',
                    'text' => lang('wechat_menu'),
                    'url' => (string) url('Wechat/menu')
                ),
            );
        }
        return $menu_array;
    }

}
